package com.run.guifeng.controller.admin;


import com.run.guifeng.commom.Constants;
import com.run.guifeng.model.entity.GoodsCategory;
import com.run.guifeng.model.entity.GoodsInfo;
import com.run.guifeng.model.enums.CategoryLevelEnum;
import com.run.guifeng.model.enums.ServiceResultEnum;
import com.run.guifeng.service.CategoryService;
import com.run.guifeng.service.GoodsService;
import com.run.guifeng.util.Result;
import com.run.guifeng.util.ResultGenerator;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @author sky
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class GoodsController {

    @Resource
    private GoodsService goodsService;
    @Resource
    private CategoryService categoryService;

    @GetMapping("/goods/edit")
    @ApiOperation("Edit goods")
    public void edit(HttpServletRequest request) {
        request.setAttribute("path", "edit");
        //查询所有的一级分类
        List<GoodsCategory> firstLevelCategories = categoryService
                .selectByLevelAndParentIdsAndNumber(Collections.singletonList(0),
                        CategoryLevelEnum.LEVEL_ONE.getLevel());
        if (!CollectionUtils.isEmpty(firstLevelCategories)) {
            //查询一级分类列表中第一个实体的所有二级分类
            List<GoodsCategory> secondLevelCategories = categoryService
                    .selectByLevelAndParentIdsAndNumber(Collections.singletonList(firstLevelCategories.get(0).
                            getId()), CategoryLevelEnum.LEVEL_TWO.getLevel());
            if (!CollectionUtils.isEmpty(secondLevelCategories)) {
                //查询二级分类列表中第一个实体的所有三级分类
                List<GoodsCategory> thirdLevelCategories = categoryService.
                        selectByLevelAndParentIdsAndNumber(Collections.singletonList(secondLevelCategories.
                                get(0).getId()), CategoryLevelEnum.LEVEL_THREE.getLevel());
                request.setAttribute("firstLevelCategories", firstLevelCategories);
                request.setAttribute("secondLevelCategories", secondLevelCategories);
                request.setAttribute("thirdLevelCategories", thirdLevelCategories);
                request.setAttribute("path", "goods-edit");
            }
        }
    }

    @GetMapping("/goods/edit/{goodsId}")
    @ApiOperation("Edit good by good id")
    public String edit(HttpServletRequest request, @PathVariable("goodsId") Integer goodsId) {
        request.setAttribute("path", "edit");
        GoodsInfo newBeeMallGoods = goodsService.getMallGoodsById(goodsId);
        if (newBeeMallGoods == null) {
            return "error";
        }
        if (newBeeMallGoods.getGoodsCategoryId() > 0) {
            if (newBeeMallGoods.getGoodsCategoryId() != null || newBeeMallGoods.getGoodsCategoryId() > 0) {
                //有分类字段则查询相关分类数据返回给前端以供分类的三级联动显示
                GoodsCategory currentGoodsCategory = categoryService.getGoodsCategoryById(newBeeMallGoods.getGoodsCategoryId());
                //商品表中存储的分类id字段为三级分类的id，不为三级分类则是错误数据
                if (currentGoodsCategory != null && currentGoodsCategory.getCategoryLevel() == CategoryLevelEnum.LEVEL_THREE.getLevel()) {
                    //查询所有的一级分类
                    List<GoodsCategory> firstLevelCategories = categoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(0), CategoryLevelEnum.LEVEL_ONE.getLevel());
                    //根据parentId查询当前parentId下所有的三级分类
                    List<GoodsCategory> thirdLevelCategories = categoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(currentGoodsCategory.getParentId()), CategoryLevelEnum.LEVEL_THREE.getLevel());
                    //查询当前三级分类的父级二级分类
                    GoodsCategory secondCategory = categoryService.getGoodsCategoryById(currentGoodsCategory.getParentId());
                    if (secondCategory != null) {
                        //根据parentId查询当前parentId下所有的二级分类
                        List<GoodsCategory> secondLevelCategories = categoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(secondCategory.getParentId()), CategoryLevelEnum.LEVEL_TWO.getLevel());
                        //查询当前二级分类的父级一级分类
                        GoodsCategory firestCategory = categoryService.getGoodsCategoryById(secondCategory.getParentId());
                        if (firestCategory != null) {
                            //所有分类数据都得到之后放到request对象中供前端读取
                            request.setAttribute("firstLevelCategories", firstLevelCategories);
                            request.setAttribute("secondLevelCategories", secondLevelCategories);
                            request.setAttribute("thirdLevelCategories", thirdLevelCategories);
                            request.setAttribute("firstLevelCategoryId", firestCategory.getId());
                            request.setAttribute("secondLevelCategoryId", secondCategory.getId());
                            request.setAttribute("thirdLevelCategoryId", currentGoodsCategory.getId());
                        }
                    }
                }
            }
        }
        if (newBeeMallGoods.getGoodsCategoryId() == 0) {
            //查询所有的一级分类
            List<GoodsCategory> firstLevelCategories = categoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(0), CategoryLevelEnum.LEVEL_ONE.getLevel());
            if (!CollectionUtils.isEmpty(firstLevelCategories)) {
                //查询一级分类列表中第一个实体的所有二级分类
                List<GoodsCategory> secondLevelCategories = categoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(firstLevelCategories.get(0).getId()), CategoryLevelEnum.LEVEL_TWO.getLevel());
                if (!CollectionUtils.isEmpty(secondLevelCategories)) {
                    //查询二级分类列表中第一个实体的所有三级分类
                    List<GoodsCategory> thirdLevelCategories = categoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(secondLevelCategories.get(0).getId()), CategoryLevelEnum.LEVEL_THREE.getLevel());
                    request.setAttribute("firstLevelCategories", firstLevelCategories);
                    request.setAttribute("secondLevelCategories", secondLevelCategories);
                    request.setAttribute("thirdLevelCategories", thirdLevelCategories);
                }
            }
        }
        request.setAttribute("goods", newBeeMallGoods);
        request.setAttribute("path", "goods-edit");
        return "success";
    }

    /**
     * 列表
     */
    @GetMapping("/goods/list")
    @ApiOperation("List all goods")
    public Result list(@RequestParam Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("current")) || StringUtils.isEmpty(params.get("size"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        return ResultGenerator.genSuccessResult(goodsService.getMallGoodsPage(
                Integer.parseInt(params.get("current").toString()),
                Integer.parseInt(params.get("size").toString()),
                null, null, null, null));
    }

    /**
     * 添加
     */
    @PostMapping("/goods/save")
    @ApiOperation("Save goods")
    public Result save(@RequestBody GoodsInfo goodInfo) {
        if (StringUtils.isEmpty(goodInfo.getGoodsName())
                || StringUtils.isEmpty(goodInfo.getGoodsIntro())
                || StringUtils.isEmpty(goodInfo.getTag())
                || Objects.isNull(goodInfo.getOriginalPrice())
                || Objects.isNull(goodInfo.getGoodsCategoryId())
                || Objects.isNull(goodInfo.getSellingPrice())
                || Objects.isNull(goodInfo.getStockNum())
                || Objects.isNull(goodInfo.getStatus())
                || StringUtils.isEmpty(goodInfo.getGoodsCoverImg())
                || StringUtils.isEmpty(goodInfo.getDetail())) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = goodsService.saveMallGoods(goodInfo);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }


    /**
     * 修改
     */
    @PostMapping("/goods/update")
    @ApiOperation("Update a goods info")
    public Result update(@RequestBody GoodsInfo goodInfo) {
        if (Objects.isNull(goodInfo.getId())
                || StringUtils.isEmpty(goodInfo.getGoodsName())
                || StringUtils.isEmpty(goodInfo.getGoodsIntro())
                || StringUtils.isEmpty(goodInfo.getTag())
                || Objects.isNull(goodInfo.getOriginalPrice())
                || Objects.isNull(goodInfo.getSellingPrice())
                || Objects.isNull(goodInfo.getGoodsCategoryId())
                || Objects.isNull(goodInfo.getStockNum())
                || Objects.isNull(goodInfo.getStatus())
                || StringUtils.isEmpty(goodInfo.getGoodsCoverImg())
                || StringUtils.isEmpty(goodInfo.getDetail())) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = goodsService.updateMallGoods(goodInfo);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * 详情
     */
    @GetMapping("/goods/info/{id}")
    @ApiOperation("Get a goods by id")
    public Result info(@PathVariable("id") Integer id) {
        GoodsInfo goods = goodsService.getMallGoodsById(id);
        if (goods == null) {
            return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        return ResultGenerator.genSuccessResult(goods);
    }

    /**
     * 批量修改销售状态
     */
    @PutMapping("/goods/status/{sellStatus}")
    @ApiOperation("Update goods's status")
    public Result delete(@RequestBody Integer[] ids, @PathVariable("sellStatus") int sellStatus) {
        if (ids.length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if (sellStatus != Constants.SELL_STATUS_UP && sellStatus != Constants.SELL_STATUS_DOWN) {
            return ResultGenerator.genFailResult("状态异常！");
        }
        if (goodsService.batchUpdateSellStatus(ids, sellStatus).equals(ServiceResultEnum.SUCCESS.getResult())) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("修改失败");
        }
    }

}